//
//  OAuthViewController.swift
//  MyLottery
//
//  Created by wujunjie on 2018/7/19.
//  Copyright © 2018年 wujunjie. All rights reserved.
//

import UIKit
import Alamofire
//MARK: -生命周期函数
class OAuthViewController: UIViewController  {
    lazy var webView : UIWebView = {
        let    webView = UIWebView(frame: kScreenBounds)
        webView.delegate = self
        return webView
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupUI()
       //加载用户登录页面
        loadLoginPage()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

//MARK:设置 UI
extension OAuthViewController{
    private func setupUI(){
        view.addSubview(webView)
    }
}
//MARK:UIWebViewDelegate
extension OAuthViewController : UIWebViewDelegate{
    //MARK:如果要网页显示就 true
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //如果 urlString 是百度,说明点击过了授权或者是取消按钮,不显示百度页面 return false
        if let urlString = request.url?.absoluteString, urlString.hasPrefix(rediretURL){
            //显示网址后的?参数
            if let queryString = request.url?.query, queryString.hasPrefix("code="){   //表示点击的是授权按钮
                let code = queryString.substring(from: "code=".endIndex)
                //根据code 获取 accessToken
                getAccessToken(code: code) { (responseObject) in
                    if let responseDic = responseObject as? [String : AnyObject],let uid = responseDic["uid"] as? String,let accessToken = responseDic["access_token"] as? String {
                        let ss: NSString = (uid as NSString)
                        let userId: UInt64 = UInt64(ss.longLongValue)
                        ///获取用户信息
                        getUserInfo(accessToken: accessToken, uid: userId, finish: { (userInfoResponse) in
                            if var userInfoDic = userInfoResponse as? [String:AnyObject]{
                                for(k,v) in responseDic{
                                    userInfoDic[k] = v
                                }
                                ///发送登录成功的通知
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: loginSuccessNotificationKey), object: self)
                                //存储用户的信息
                                UserInfoModel.userAccount.saveUserAccount(dict: userInfoDic)
                                self.dismiss(animated: true, completion: nil)
                            }
                        })
                    }
                }
            } else{  //点击的是取消按钮
                dismiss(animated: true, completion: nil)
            }
            return false
        }
        return true
    }
    //网页加载完成之后,调用该方法,调用 js 必须在这个位置
    func webViewDidFinishLoad(_ webView: UIWebView) {
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value=\(weiBoId);document.getElementById('passwd').value=\(weiBoPassword)")
    }
}

//MARK:-点击事件
extension OAuthViewController{
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dismiss(animated: true, completion: nil)
    }
}
//MARK:加载登录
extension OAuthViewController {
    //加载用户登录页面
    func loadLoginPage () {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=4255870175&redirect_uri=https://baidu.com"
        let url = URL(string: urlString)
        let request = NSURLRequest(url: url!)
        webView.loadRequest(request as URLRequest)
    }
}

